package com.ziqi.hututubackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.ziqi.hututubackend.config.CosClientConfig;
import com.ziqi.hututubackend.exception.BusinessException;
import com.ziqi.hututubackend.exception.ErrorCode;
import com.ziqi.hututubackend.exception.ThrowUtils;
import com.ziqi.hututubackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Deprecated
@Service
@Slf4j
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile 文件
     * @param uploadPathPrefix  上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16); //随机16字符的占位符
        String originFilename  = multipartFile.getOriginalFilename();
        // 设置更新后的文件名，格式化  (当前日期 + 随机字符。 + 图片后缀)
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFilename));
        // 设置更新后的文件路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            //1.创建临时文件
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            //2.上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 3.封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
            //设置图片宽度
            int picWidth = imageInfo.getWidth();
            uploadPictureResult.setPicWidth(picWidth);
            //设置图片高度
            int picHeight = imageInfo.getHeight();
            uploadPictureResult.setPicHeight(picHeight);
            // 计算图片比例并赋值
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicScale(picScale);
            // 图片格式
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            // 图片尺寸
            uploadPictureResult.setPicSize(FileUtil.size(file));
            // 赋值图片url地址, ----- 主机地址 + 相对地址就是绝对地址
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadPictureResult;

        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            // 上传完成后删除
        } finally {
            this.deleteTempFile(file);
        }

    }

    /**
     * 根据 Url上传图片
     * @param fileUrl 文件url
     * @param uploadPathPrefix  上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        validPicture(fileUrl);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16); //随机16字符的占位符
//        String originFilename  = multipartFile.getOriginalFilename();
        // 根据url获取图片名称
        String originFilename  = FileUtil.mainName(fileUrl);
        // 设置更新后的文件名，格式化  (当前日期 + 随机字符。 + 图片后缀)
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFilename));
        // 设置更新后的文件路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            //  1.创建临时文件
            file = File.createTempFile(uploadPath, null);
//            multipartFile.transferTo(file);
            //从url下载图片文件到file临时对象
            HttpUtil.downloadFile(fileUrl, file);

            //2.上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 3.封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
            //设置图片宽度
            int picWidth = imageInfo.getWidth();
            uploadPictureResult.setPicWidth(picWidth);
            //设置图片高度
            int picHeight = imageInfo.getHeight();
            uploadPictureResult.setPicHeight(picHeight);
            // 计算图片比例并赋值
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicScale(picScale);
            // 图片格式
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            // 图片尺寸
            uploadPictureResult.setPicSize(FileUtil.size(file));
            // 赋值图片url地址, ----- 主机地址 + 相对地址就是绝对地址
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadPictureResult;

        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            // 上传完成后删除
        } finally {
            this.deleteTempFile(file);
        }

    }

    /**
     * 本地上传校验文件
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1、校验文件大小
        long fileSize = multipartFile.getSize();  //获取文件大小
        final long ONE_M = 1024 * 1024L;  //定义1m大小
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
        // 2、校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename()); //获取文件后缀
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型不支持");
    }

    /**
     * url 上传校验文件
     * @param fileUrl 图片url
     */
    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(fileUrl == null, ErrorCode.PARAMS_ERROR, "图片url不能为空");
        // 1, 校验url地址格式
        try {
            new URL(fileUrl); //调用java自带方法检验是否为合法URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片地址格式不正确");
        }

        // 2. 校验 url 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")), ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议文件地址");

        // 3. 发送HEAD请求验证文件是否存在
        HttpResponse response = null;
        try {
            // 创建head请求执行
            HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正常返回，无需执行其他判断
            if(response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if(StrUtil.isNotBlank(contentType)) {
                // 允许上传的文件类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()), ErrorCode.PARAMS_ERROR, "文件类型不支持");
            }
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-length");
            if(StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为2MB；
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "图片大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            // 清除本地临时文件
            if(response != null) {
                response.close();
            }
        }
    }


    /**
     * 删除临时文件
     * @param file
     */
    public void deleteTempFile(File file) {
        if(file == null) return;
        //删除临时文件
        boolean deleteResult = file.delete();
        if(!deleteResult) {
            log.error("文件删除失败，文件路径 = {}", file.getAbsolutePath());
        }
    }
}
